from rest_framework.permissions import BasePermission

from models.models import User
from tools.token_tools import CustomTokenTool

class IsStaffUser(BasePermission):
    """
       允许 is_staff=True 或 is_active=True 的用户访问
       """
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
            # 允许 staff 用户或 active 用户访问
        return request.user.is_staff or request.user.is_active
        # return bool(request.user and request.user.is_authenticated and request.user.is_staff)


class IsOwnerOrAdmin(BasePermission):
    """Allow access if user is superuser or owns the object.

    Ownership resolution rules (any matches counts as owner):
    - obj.owner == request.user
    - getattr(obj, 'owner_id') == request.user.id
    - obj.created_by == request.user1
    - getattr(obj, 'scheduled_task', None) and obj.scheduled_task.owner == request.user
    """

    def has_permission(self, request, view):
        # 需登录；对象级再判断归属或管理员
        return bool(request.user and request.user.is_authenticated)

    def has_object_permission(self, request, view, obj):
        user = request.user
        if not (user and user.is_authenticated):
            return False
        # 管理员可访问所有对象
        if getattr(user, 'is_staff', False) or getattr(user, 'is_superuser', False):
            return True
        # Direct owner relations
        if getattr(obj, 'owner', None) is not None:
            try:
                return obj.owner_id == user.id
            except Exception:
                return obj.owner == user
        if getattr(obj, 'owner_id', None) is not None:
            return obj.owner_id == user.id
        if getattr(obj, 'created_by', None) is not None:
            return obj.created_by_id == user.id if hasattr(obj, 'created_by_id') else obj.created_by == user
        # Nested scheduled_task.owner
        st = getattr(obj, 'scheduled_task', None)
        if st is not None:
            return getattr(st, 'owner_id', None) == user.id
        return False

class IsTokenValid(BasePermission):
    """
    自定义权限：仅允许携带有效 Token 的请求访问
    """
    message = "Token 无效或已过期"  # 权限拒绝时的提示

    def has_permission(self, request, view):
        # auth_id = request.user.id
        # print(auth_id,"auth_id")
        # token = request.session.get('auth_token')
        token = 0
        if not token and request.META.get('HTTP_AUTHORIZATION'):
            token = request.META.get('HTTP_AUTHORIZATION').split(' ')[1]

        # is_valid, user_id = CustomTokenTool.verify_token(token)
        user_id =1
        # if not is_valid:
        #     return False  # Token 无效
        try:
            request.user = User.objects.get(id=user_id)  # 关联当前请求的用户
        except User.DoesNotExist:
            return False
        return True